package com.atmc.service.impl;

import com.atmc.entity.AcomentNum;
import com.atmc.entity.Article;
import com.atmc.entity.ResponseResult;
import com.atmc.entity.User;
import com.atmc.mapper.ArtImagesMapper;
import com.atmc.mapper.ArticleMapper;
import com.atmc.mapper.HeadPotraitMapper;
import com.atmc.service.AcomentNumService;
import com.atmc.service.ArticleService;
import com.atmc.service.UserService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @BelongsProject: SpringCloud1216
 * @BelongsPackage: com.atmc.service.impl
 * @Author: chuyings
 * @CreateTime: 2022-11-11  13:17
 * @Version: 1.0
 */
@Service
public class ArticleServiceImpl implements ArticleService{
    @Autowired
    @Qualifier("minioClient")
    MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    UserService userService;
    @Autowired
    HeadPotraitMapper headPotraitMapper;
    @Autowired
    AcomentNumService acomentNumService;
    @Autowired
    ArtImagesMapper artImagesMapper;
//    @Override
//    public Long selectOneById(String userName) {
//        return articleMapper.selectOneById(userName);
//    }

    @Override
    public List<Article> selectAll() {
        List<Article> list = articleMapper.selectAll();
        return list;
    }

    @Override
    public List<String> queryById(Long articleId) {
        return articleMapper.queryById(articleId);
    }

    @Override
    public ResponseResult getArticleAll() {
        List<Article> articles = articleMapper.selectAll();
        Map<Long, Article> map = new HashMap<>();
        Article rootNode = null;
        for (Article article : articles) {
            String userName = article.getUserName();
            User user = userService.selectOne(userName);
            Long userId = user.getUserId();
            String fileUrl = headPotraitMapper.selectOneUrl(userId);
            article.setFileUrl(fileUrl);
            Long articleId = article.getId();
            map.put(articleId, article);
        }
        for (Article particle : articles) {
            Long pId = particle.getFId();
            if (pId == null) {
                rootNode = particle;
                continue;
            }
            Article fatherNode = map.get(pId);
            fatherNode.getChildren().add(particle);

            map.put(pId, fatherNode);
        }
        List<Article> list = new ArrayList<>();

        Collection<Article> values = map.values();
        //得到根节点以及孩子节点 返回前端
        for (Article value : values) {
            Long pId = value.getFId();
            Long id = value.getId();
            if (pId == null) {
                list.add(value);
            }
        }
        for (Article article : list) {
            Long id = article.getId();
            List<String> list1 = articleMapper.queryById(id);
            AcomentNum acomentNum = acomentNumService.queryById(id);
            article.setCommentNum(acomentNum.getCommentNum());
            article.setArtPhoto(list1);
        }
        //帖子转成倒序
        Collections.sort(list, new Comparator<Article>() {
            @Override
            public int compare(Article o1, Article o2) {

                return -o1.getId().compareTo(o2.getId());
            }
        });
        return new ResponseResult(200, "所有帖子数据", list);
    }

    @Override
    public int insertArticleOne(Article article) {
        Long id = article.getId();
        acomentNumService.updateOne(id);
        return articleMapper.insertArticleOne(article);
    }

    @Override
    public int updateOneLikerCre(Long articleId) {
        return articleMapper.updateOneLikerCre(articleId);
    }
    @Override
    public int updateOneLikerDes(Long articleId) {
        return articleMapper.updateOneLikerDes(articleId);
    }

    @Override
    public ResponseResult publishPost(String context, String userName, List<MultipartFile> artPhoto) {
        if (artPhoto == null || artPhoto.size()==0) {
            return new ResponseResult(400,"上传失败");
        }
        Article article=new Article();
        article.setContext(context);
        article.setUserName(userName);
        articleMapper.insertArticleOne(article);
        for (MultipartFile multipartFile : artPhoto) {
            String originalFilename = multipartFile.getOriginalFilename();
            InputStream inputStream = null;
            try {
//                String bucketName = "chuyings";
                boolean exists =
                        minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
                if (!exists) {
                    // 不存在，创建bucket
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
//                    SetBucketPolicyArgs setBucketPolicyArgs=new SetBucketPolicyArgs();
//                    minioClient.setBucketPolicy();
//                    SetBucketPolicyArgs.Builder bucket = SetBucketPolicyArgs.builder().bucket("chuyings").config("Private");
//                    minioClient.setBucketPolicy(setBucketPolicyArgs);
                }
                inputStream = multipartFile.getInputStream();
                minioClient.putObject(
                        PutObjectArgs
                                .builder()
                                .bucket(bucketName)
                                .object(multipartFile.getOriginalFilename())
                                .stream(inputStream,multipartFile.getSize(),-1)
                                .contentType(multipartFile.getContentType())
                                .build());

            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (inputStream !=null){
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String fileUrls="http://43.143.140.144:9000/"+bucketName+"/"+originalFilename;
            artImagesMapper.insertPhotos(article.getId(),fileUrls);
            AcomentNum acomentNum = acomentNumService.queryById(article.getId());
            if (Objects.isNull(acomentNum)){
                acomentNumService.insertOne(article.getId());
            }
        }
        return new ResponseResult(200,"发布成功");
    }

    @Override
    public ResponseResult commentPost(Article articleOne) {
        //帖子id
        Long tieZiId = articleOne.getId();
        acomentNumService.updateOne(tieZiId);
        articleOne.setId(null);
        articleMapper.insertArticleOne(articleOne);

        List<Article> articles = articleMapper.selectAll();

        Map<Long, Article> map = new HashMap<>();
        Article rootNode = null;
        for (Article article : articles) {
            String userName = article.getUserName();
            User user = userService.selectOne(userName);
            Long userId = user.getUserId();
            String fileUrl = headPotraitMapper.selectOneUrl(userId);
            article.setFileUrl(fileUrl);
            Long articleId = article.getId();
            map.put(articleId, article);
        }
        for (Article particle : articles) {
            Long FId = particle.getFId();
            if (FId == null) {
                rootNode = particle;
                continue;
            }
            Article fatherNode = map.get(FId);
            fatherNode.getChildren().add(particle);

            map.put(FId, fatherNode);
        }
        Article article = map.get(tieZiId);

        return new ResponseResult(200,"回复成功",article);
    }

    @Override
    public List<Article> selectByUserName(String userName) {
        List<Article> articles = articleMapper.selectAll();

        Map<Long, Article> map = new HashMap<>();
        Article rootNode = null;
        for (Article article : articles) {
            String userName1 = article.getUserName();
            User user = userService.selectOne(userName1);
            Long userId = user.getUserId();
            String fileUrl = headPotraitMapper.selectOneUrl(userId);
            article.setFileUrl(fileUrl);
            Long articleId = article.getId();
            map.put(articleId, article);
        }
        for (Article particle : articles) {
            Long FId = particle.getFId();
            if (FId == null) {
                rootNode = particle;
                continue;
            }
            Article fatherNode = map.get(FId);
            fatherNode.getChildren().add(particle);

            map.put(FId, fatherNode);
        }
        List<Article> list = new ArrayList<>();

        Collection<Article> values = map.values();
        //得到根节点以及孩子节点 返回前端
        for (Article value : values) {
            Long pId = value.getFId();
            Long id = value.getId();
            if (pId == null) {
                list.add(value);
            }
        }
        for (Article article : list) {
            Long id = article.getId();
            List<String> list1 = articleMapper.queryById(id);
            AcomentNum acomentNum = acomentNumService.queryById(id);
            article.setCommentNum(acomentNum.getCommentNum());
            article.setArtPhoto(list1);
        }
        List<Article> articleByUserNameList = new ArrayList<>();
        for (Article article : list) {
            if (article.getFId()==null&&article.getUserName().equals(userName)){
                articleByUserNameList.add(article);
            }
        }
        return articleByUserNameList;
    }
}
